package com.ybt.service.manager;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;

import com.ybt.configration.IYBTConfigration;
import com.ybt.configration.YBTConfigration;
import com.ybt.configration.YBTRuntimeConfiguration;
import com.ybt.pub.XmlUtil;
import com.ybt.service.IService;
import com.ybt.service.IServiceConstants;
import com.ybt.service.impl.ServiceWapped;

public class ServiceManager {
    private static Logger logger = Logger.getLogger(ServiceManager.class);
    private static String CONFIG_DIR = "service" + File.separator
            + "service.xml";
    private Map<String, ServiceWapped> services;

    private volatile static ServiceManager manager;

    private ServiceManager() {
        services = new HashMap<String, ServiceWapped>();

        CONFIG_DIR = YBTConfigration.getInstance().getProperty(
                IYBTConfigration.WORKFLOW_DEPLOY_PATH)
                + File.separator + CONFIG_DIR;

        loadFromLocal();
    }

    public static ServiceManager getInstance() {
        if (manager == null) {
            synchronized (ServiceManager.class) {
                if (manager == null) {
                    manager = new ServiceManager();
                }
            }
        }
        return manager;
    }

    /**
     * 根据服务名称，获取服务对象.
     * 
     * @param name
     *            服务名称
     * @return 服务对象
     */
    public IService createService(String name) {
        ServiceWapped service = services.get(name);
        if (service == null) {
            throw new RuntimeException("unsupport service, service name ["
                    + name + "]");
        }
        return service.getService();
    }

    private void loadFromLocal() {

        File file = new File(CONFIG_DIR);
        if (!file.exists()) {
            throw new RuntimeException("can't find the configration file : "
                    + CONFIG_DIR);
        }

        try {
            Document doc = XmlUtil.loadXml(CONFIG_DIR, YBTRuntimeConfiguration
                    .getInstance().getConfigFileCharset());
            List<Element> tasks = doc.getRootElement().elements("service");
            for (Element et : tasks) {
                String name = et.attributeValue("name");
                String type = et.attributeValue("type");
                if(null == type){
                    type = IServiceConstants.ATOM_SERVICE;
                }else if(type.equals(IServiceConstants.ATOM_SERVICE)){
                    type = IServiceConstants.ATOM_SERVICE;
                }else if(type.equals(IServiceConstants.COMPOSE_SERVICE)){
                    type = IServiceConstants.COMPOSE_SERVICE;
                }else{
                    throw new RuntimeException("unsupport service type for service ["
                            + name + "]");
                }
                String implement = et.element("implement").getText();
                logger.debug("load service define [" + name + " : " + implement
                        + "]");

                try {
                    // 初始化工作流任务
                    Class c = Class.forName(implement);
                    IService service = (IService) c.newInstance();
                    ServiceWapped w = new ServiceWapped();
                    w.setName(name);
                    w.setType(type);
                    w.setService(service);
                    services.put(name, w);
                } catch (Exception e) {
                    throw new RuntimeException("initialize service error :"
                            + implement, e);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("parse configration file error : "
                    + CONFIG_DIR, e);
        }
    }
}
